package com.example.yuwei.registerlogin_system.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.yuwei.registerlogin_system.R;
import com.example.yuwei.registerlogin_system.bean.User;
import com.example.yuwei.registerlogin_system.presenter.LoginPresenter;


/**
 * LoginActivity
 *
 * @author yuwei
 * @date 2019/1/10
 */
public class LoginActivity extends AppCompatActivity implements LoginView {
    private EditText et_userName;
    private EditText et_passWord;
    private Button btn_Login;
    private String userName;
    private String passWord;
    private LoginPresenter loginPresenter;
    private static final int CONNECT_ERROR = 0;
    private static final int SUCCESS = 1;
    private static final int FAILURE = 2;
    private static final int URL_ISEMPTY = 3;
    private static final int CONNECT_TIMEOUT = 4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        loginPresenter = new LoginPresenter(this);
        init();
    }


    /**
     * 注册按钮的响应
     *
     * @param view
     */
    public void register(View view) {
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);

    }

    public void init() {
        et_userName = findViewById(R.id.username);
        et_passWord = findViewById(R.id.password1);
        btn_Login = findViewById(R.id.Login_Button);
        //登录按键的响应
        btn_Login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkOut()) {
                    loginPresenter.login();
                }
            }
        });
    }

    /**
     * 检查用户的输入是否为空
     */
    public boolean checkOut() {
        userName = et_userName.getText().toString().trim();
        passWord = et_passWord.getText().toString().trim();

        if (TextUtils.isEmpty(userName)) {
            Toast.makeText(LoginActivity.this, getResources().getString(R.string.username_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }

        if (TextUtils.isEmpty(passWord)) {
            Toast.makeText(LoginActivity.this, getResources().getString(R.string.pass_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 发送用户的信息给服务器
     */


    /**
     * 通过用户名返回密码，没有密码则返回  “”
     *
     * @param key
     * @return
     */
    public String getSharedPreference(String key) {
        String regularEx = "#";
        String[] str = null;
        SharedPreferences sp = getSharedPreferences("loginInfo", MODE_PRIVATE);
        String values;
        values = sp.getString(key, "");

        str = values.split(regularEx);

        if (str.length > 1) {
            return str[1];
        } else {
            return "";
        }
    }

    /**
     * 将登录的状态保存到sharedpreference
     */

    private void saveLoginStatus(boolean status, String username) {

        // loginInfo表示文件名
        SharedPreferences sp = getSharedPreferences("loginInfo", MODE_PRIVATE);
        //获取编辑器
        SharedPreferences.Editor editor = sp.edit();
        //存入登录状态
        editor.putBoolean("islogin", status);
        //提交修改
        editor.commit();
    }

    /**
     * 判断是否存在用户名
     */
    private boolean isExistUsername(String username) {
        boolean hasUsername = false;
        String str = getSharedPreference(username);
        if (str != null && !(str.equals(""))) {
            hasUsername = true;
            System.out.println(str);
        }

        return hasUsername;

    }



    @Override
    public User setData(User user) {
        if(user == null){return user;}
        user.setUserName(et_userName.getText().toString().trim());
        user.setPassWord(et_passWord.getText().toString().trim());
        return user;
    }

    @Override
    public Handler showMessage() {
        @SuppressLint("HandlerLeak") Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case CONNECT_ERROR:
                        Toast.makeText(LoginActivity.this, getResources().getString(R.string.connect_error), Toast.LENGTH_SHORT).show();
                        break;
                    case SUCCESS:
                        Toast.makeText(LoginActivity.this, getResources().getString(R.string.login_success), Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(LoginActivity.this, webActivity.class));
                        LoginActivity.this.finish();
                        break;
                    case FAILURE:
                        Toast.makeText(LoginActivity.this, getResources().getString(R.string.login_fail), Toast.LENGTH_SHORT).show();
                        break;
                    case URL_ISEMPTY:
                        Log.e("input error", "url为空");
                        break;
                    case CONNECT_TIMEOUT:
                        Toast.makeText(LoginActivity.this, getResources().getString(R.string.connect_timeout), Toast.LENGTH_SHORT).show();
                        break;
                    default:
                }
            }
        };
        return handler;
    }
}
